package main;

import java.util.HashMap;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;

public class MyHandler extends DefaultHandler
{
		private String _currentIdPath = "";
		private int _nodeId = 0;
		
		/*
		 * will hold the mapping between node's id to the route's id
		 */
		private HashMap<Integer,Integer> _nodeIdToRoutIdMap;
		
		/*
		 *  will hold the mapping between serialized route to the route's index 
		 */
		private HashMap<Integer,String> _routeIdToSerializedRouteMap;
		
		/*
		 * will hold the mapping between the labelId to the label's name
		 */
		private HashMap<Integer,String> _labelIdToLabelMap;
		
		private HashMap<String,Integer> _labelToLabelIdMap;
		private HashMap<String,Integer> _serializedRouteToRouteIdMap;
		
		public MyHandler( HashMap<Integer,Integer> nodeIdToRoutIdMap,HashMap<Integer,String> routeIdToSerializedRouteMap,HashMap<Integer,String> labelIdToLabelMap)
		{
			_nodeIdToRoutIdMap = nodeIdToRoutIdMap;
			_routeIdToSerializedRouteMap = routeIdToSerializedRouteMap;
			_labelIdToLabelMap = labelIdToLabelMap;
			
			//helpers DAST for not making any duplications. if we have some data already, make reference to it
			_labelToLabelIdMap = new HashMap<String, Integer>();
			_serializedRouteToRouteIdMap = new HashMap<String, Integer>();
		}
		
		public void startElement(String uri, String localName, String qName, Attributes attributes)  {
			_nodeId++;
			
			
			//update current path
			if (!_currentIdPath.isEmpty())
			{
				_currentIdPath+="#";
			}
			
			if (!_labelToLabelIdMap.containsKey(qName))
			{
				_labelToLabelIdMap.put(qName, _nodeId);
				_labelIdToLabelMap.put(_nodeId, qName);
			}
			
			_currentIdPath += String.valueOf(_labelToLabelIdMap.get(qName));
			//connect current node with current path
			int routeId;
			if (!_serializedRouteToRouteIdMap.containsKey(_currentIdPath))
			{
				routeId = _serializedRouteToRouteIdMap.size();
				_serializedRouteToRouteIdMap.put(_currentIdPath, routeId);
				_routeIdToSerializedRouteMap.put(routeId, _currentIdPath);
			}
			else
			{
				routeId = _serializedRouteToRouteIdMap.get(_currentIdPath);
			}
			
			_nodeIdToRoutIdMap.put(_nodeId,routeId);
		}
	 
		public void endElement(String uri, String localName,
			String qName) throws SAXException {
	 
			int sepIndex = _currentIdPath.lastIndexOf("#");
			
			if (sepIndex == -1)
			{
				_currentIdPath = "";
			}
			else
			{
				_currentIdPath = _currentIdPath.substring(0, sepIndex);
			}
	 
		}
	 
		
}